package com.intel.factorytest.activity;

import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import com.intel.factorytest.util.AutoFocusManager;

import com.intel.factorytest.R;

public class Camera extends BaseActivity implements SurfaceHolder.Callback {
    private static final String TAG = "Camera";
    private Button mSucBtn;
    private Button mFailBtn;
    private Button mRepeatBtn;

    private SurfaceView mCameraView = null;
    private Button mPreviewButton, mCaptureButton, mDeleteButton,
            mTurnOffButton;
    private android.hardware.Camera mCameraDevice = null;
    private Parameters parameters = null;
    SurfaceHolder holder;
    private TextView mcTestText;
    private int cameraId = 0;
    private String FlashMode;

    private AutoFocusManager autoFocusManager;

    public void onCreate(Bundle b) {
        super.onCreate(b);
        Log.i(TAG, "onCreate() ");
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.camera_test);
        initView();

        this.getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        mCameraView = (SurfaceView) findViewById(R.id.cameraView);

        mcTestText = new TextView(this);
        mcTestText.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
        mcTestText.setGravity(Gravity.CENTER);
        mcTestText.setTextSize(16);

        holder = mCameraView.getHolder();
        holder.addCallback(this);
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        // openCamerawithholder();
        //
        // mCameraDevice.startPreview();
        // mCameraDevice.setDisplayOrientation(getDisplayOrientation(
        // getDisplayRotation(this), cameraId));

    }

    protected void initView() {
        mSucBtn = (Button) findViewById(R.id.successbutton);
        mFailBtn = (Button) findViewById(R.id.failbutton);
        mRepeatBtn = (Button) findViewById(R.id.repeatbutton);
        mSucBtn.setEnabled(false);
        mFailBtn.setEnabled(false);
        mRepeatBtn.setEnabled(false);

        mSucBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                v.setClickable(false);
                is_pass = true;
                finish();
            }
        });

        mFailBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                v.setClickable(false);
                is_pass = false;
                finish();
            }
        });

        mRepeatBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                recreate();
            }
        });

    }

    public void onResume() {
        Log.i(TAG, "onResume() ");
        super.onResume();
        openCamerawithholder();
        Log.d(TAG, "openCamerawithholder ok ");

//        try {
//            mCameraDevice.startPreview();
//            mCameraDevice.setDisplayOrientation(getDisplayOrientation(
//                    getDisplayRotation(this), cameraId));
//        } catch (NullPointerException e) {
//            e.printStackTrace(System.err);
//        }
        
        mSucBtn.setEnabled(true);
        mFailBtn.setEnabled(true);
        mRepeatBtn.setEnabled(true);

    }

    public int getDisplayRotation(Activity activity) {
        int rotation = activity.getWindowManager().getDefaultDisplay()
                .getRotation();
        Log.d(TAG, "rotation:"+rotation);
        switch (rotation) {
        case Surface.ROTATION_0:
            return 0;
        case Surface.ROTATION_90:
            return 90;
        case Surface.ROTATION_180:
            return 180;
        case Surface.ROTATION_270:
            return 270;
        }
        return 0;
    }

    public int getDisplayOrientation(int degrees, int cameraId) {
        android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
        android.hardware.Camera.getCameraInfo(cameraId, info);
        int result;
        if (info.facing == android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360;
            Log.i(TAG, "info.orientation = " + info.orientation
                    + "  degrees = " + degrees + " result = " + result);
        } else {
            result = (info.orientation - degrees + 360) % 360;
            Log.i(TAG, "info.orientation = " + info.orientation
                    + "  degrees = " + degrees + " result = " + result);
        }
        return result;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        Log.i(TAG, "onConfigurationChanged() ");
        super.onConfigurationChanged(newConfig);
        if (mCameraDevice != null) {
            mCameraDevice.setDisplayOrientation(getDisplayOrientation(
                    getDisplayRotation(this), cameraId));
        }

    }

    private void openCamerawithholder() {
        mCameraView.setVisibility(View.GONE);
        if (2 == android.hardware.Camera.getNumberOfCameras()) {
//            Log.d(TAG, "getNumberOfCameras.....2 ");
            try {
                mCameraDevice = android.hardware.Camera.open(0);// for the big
                                                                // camera yjcui
                
                parameters = mCameraDevice.getParameters();
                // FlashMode=parameters.getFlashMode();
                // if (FlashMode!=null)
                // {
                //     parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
                // }
                mCameraDevice.setParameters(parameters);
                cameraId = 0;
            } catch (Exception e) {
//                Log.d(TAG, "camera error=====");
                //mcTestText.setText("The back camera is not available");
                //setContentView(mcTestText);
            }
        } else if (1 == android.hardware.Camera.getNumberOfCameras()) {
            Log.d(TAG, "getNumberOfCameras.....1 ");
            android.hardware.Camera.CameraInfo cameraInfo = new android.hardware.Camera.CameraInfo();
            android.hardware.Camera.getCameraInfo(0, cameraInfo);
            if (android.hardware.Camera.CameraInfo.CAMERA_FACING_BACK == cameraInfo.facing) {
                try {
                    mCameraDevice = android.hardware.Camera.open(0);// for the
                                                                    // big
                                                                    // camera
                                                                    // yjcui
                    parameters = mCameraDevice.getParameters();
                    FlashMode=parameters.getFlashMode();
                    if (FlashMode!=null)
                    {
                        parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
                    }
                    mCameraDevice.setParameters(parameters);
                    cameraId = 0;
                } catch (Exception e) {
//                    Log.d(TAG, "camera error=====");
                    //mcTestText.setText("The back camera is not available");
                    //(mcTestText);
                }
            } else {
                //mcTestText.setText("The back camera is not available");
                //setContentView(mcTestText);
            }
        } else {// not available camera
//            Log.d(TAG, "Not available camera");
            //mcTestText.setText("Not available camera");
            //setContentView(mcTestText);
        }
//        Log.d(TAG, "mCameraDevice...... "+mCameraDevice);
        //android.os.SystemProperties.set("service.camera.id", "1");

        if (autoFocusManager == null && mCameraDevice != null) {
            autoFocusManager = new AutoFocusManager(mCameraDevice);
            autoFocusManager.setAutofocusInterval(2000);
            autoFocusManager.start();
        }

        try {
            if (mCameraDevice!= null)
            {
                Log.d(TAG, "mCameraDevice.startPreview()");
                mCameraDevice.setPreviewDisplay(holder);
                mCameraView.setVisibility(View.VISIBLE);
                mCameraDevice.startPreview();
                mCameraDevice.setDisplayOrientation(getDisplayOrientation(
                        getDisplayRotation(this), cameraId));
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
//            Log.d(TAG, "startPreview error=====");
            e.printStackTrace();
        }

    }

    public void onPause() {
        super.onPause();
        Log.i(TAG, "onPause() ");
        if (autoFocusManager != null){
            autoFocusManager.stop();
            autoFocusManager = null;
        }

        if (mCameraDevice != null) {
            FlashMode=parameters.getFlashMode();
            if (FlashMode!=null)
            {
                parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
            }
            mCameraDevice.setParameters(parameters);
            mCameraDevice.stopPreview();
            mCameraDevice.release();
            mCameraDevice = null;
        }
        //android.os.SystemProperties.set("service.camera.id", "0");
    }

    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy ");
        
    }

    /**
     * total 3 states, before preview, previewing, after capture ,
     */

    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
        Log.i(TAG, "surfaceChanged width=" + width + " height=" + height);

        try {
            if (mCameraDevice != null) {
                mCameraDevice.setPreviewDisplay(holder);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public void surfaceCreated(SurfaceHolder holder) {
        // TODO Auto-generated method stub
        Log.i(TAG, "surfaceCreated ");
        // mCameraDevice = android.hardware.Camera.open(0);//for the big camera
        // yjcui
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        Log.i(TAG, "surfaceDestroyed ");
        holder.removeCallback(this);  

    }

    // private ShutterCallback mShutter = new ShutterCallback() {
    //
    // public void onShutter() {
    // Log.i("yjc", "onShutter ");
    // }
    // };
    // private PictureCallback mRaw = new PictureCallback() {
    //
    // public void onPictureTaken(byte[] data, android.hardware.Camera camera) {
    // Log.i("yjc", "mRaw " + (data == null ? "has no data" : "has data")
    // + " camera=" + camera.getParameters());
    // }
    // };
    // private PictureCallback mPostview = new PictureCallback() {
    //
    // public void onPictureTaken(byte[] data, android.hardware.Camera camera) {
    // Log.i("yjc", "mPostview " + data.length);
    // }
    // };

    @Override
    public void finish() {
        tc.setTestResult(is_pass);
        super.finish();
    }
}
